package routers

import (
	"net/url"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
)

var officialSite = map[string]struct{}{
	"opengauss.org":             {},
	"opengauss.test.osinfra.cn": {},
}

func initMiddleware() {
	beego.InsertFilter("/v1/gauss/*", beego.BeforeRouter, addHeader)
	beego.InsertFilter("/v1/gauss/*", beego.BeforeRouter, checkReferer)

}

func addHeader(ctx *context.Context) {
	ctx.ResponseWriter.Header().Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
	ctx.ResponseWriter.Header().Add("X-XSS-Protection", "1; mode=block")
	ctx.ResponseWriter.Header().Add("X-Frame-Options", "DENY")
	ctx.ResponseWriter.Header().Add("X-Content-Type-Options", "nosniff")
	ctx.ResponseWriter.Header().Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
	ctx.ResponseWriter.Header().Add("Content-Security-Policy", "script-src 'self'; object-src 'none'; frame-src 'none'")
	ctx.ResponseWriter.Header().Add("Cache-Control", "no-cache,no-store,must-revalidate")
	ctx.ResponseWriter.Header().Add("Pragma", "no-cache")
	ctx.ResponseWriter.Header().Add("Expires", "0")

}

func checkReferer(ctx *context.Context) {
	r, err := url.Parse(ctx.Request.Referer())
	if err != nil {
		ctx.WriteString("illegal referer")
		return
	}

	if _, ok := officialSite[r.Host]; !ok {
		ctx.WriteString("illegal referer")
		return
	}

}
